package com.difsonapps.android.marker.util;

import java.io.File;
import java.io.FileOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.util.Log;

import com.difsonapps.android.marker.AppConstant;

public class MarkerUtil {
	public static String buildUrl(String url, Map<String, String> params){
		String result = url;
		if(!(result.startsWith("http://") || result.startsWith("https://"))){
			if(!result.startsWith("/")) result = "/"+result;
			result = AppConstant.basePath+""+result;//TODO
		}
		for (String key : params.keySet()) {
			String value = params.get(key);
			result = result.replaceAll("\\["+key+"\\]", value);
		}
		return result;
	}
	
	public static String buildImageUrl(String fileName, String folder, String host){
		if(fileName.startsWith("http://") || fileName.startsWith("https://")) return fileName;
		String result = host!=null?host:AppConstant.basePath;
		if(!result.endsWith("/")) result += "/";
		if(folder!=null) result += folder;
		if(!result.endsWith("/")) result += "/";
		return result+fileName;
	}
	
	public static String getRelativeTime(String dateTxt, String nowTxt, Context context){
		Date date = parseDate(dateTxt);
		Date now = parseDate(nowTxt);
		if(date==null||now==null) return dateTxt;
		
		Calendar cal =Calendar.getInstance();
		cal.setTime(date);
		
		Calendar calNow =Calendar.getInstance();
		calNow.setTime(now);
		
		long millis = (calNow.getTimeInMillis() - cal.getTimeInMillis())/1000;
		//Log.e("Difference : ", ""+millis);
		boolean positive = millis>0;
		long abs = positive?millis:-millis;
		if(abs<60){
			return "just now";
		}
		if(abs<3600){
			long min = millis/60;
			if(positive) return ""+min+"min ago";
			return "in "+min+" min";
		}
		if(abs<(86400)){//Less than 01 day
			long hour = abs/3600;
			if(positive) return ""+hour+"h ago";
			return "in "+hour+"h";
		}
		if(abs<(604800)){//Less than 01 week
			long days = abs/86400;
			if(positive) return ""+days+" day"+(days>1?"s":"")+" ago";
			return "in "+days+" day"+(days>1?"s":"");
		}
		
		return dateTxt;
	}
	
	public static Date parseDate(String dateTxt){
		if(dateTxt==null || "".equals(dateTxt.trim())) return null;
		try {
			//Log.i("Converting : ", dateTxt);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date result = format.parse(dateTxt);
			//Log.w("Converted date : ", result==null?"null":result.toString());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String formatDateFromDefaultFormat(String date){
		return date;
	}
	
	public static String md5(String s) {
	    final String MD5 = "MD5";
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest
	                .getInstance(MD5);
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();

	        // Create Hex String
	        StringBuilder hexString = new StringBuilder();
	        for (byte aMessageDigest : messageDigest) {
	            String h = Integer.toHexString(0xFF & aMessageDigest);
	            while (h.length() < 2)
	                h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();

	    } catch (NoSuchAlgorithmException e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	public static File saveToInternalSorage(Bitmap bitmapImage, Context context, String dir, String fileName){
        ContextWrapper cw = new ContextWrapper(context);
         // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir(dir, Context.MODE_PRIVATE);
        // Create imageDir
        File mypath=new File(directory, fileName);

        FileOutputStream fos = null;
        try {           

            fos = new FileOutputStream(mypath);

       // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mypath;
    }
	public static File saveToInternalSorage(Bitmap bitmapImage, Context context){
        return saveToInternalSorage(bitmapImage, context, "imageDir", "image.jpg");
    }
	
	public static String abbreviate(String str, int maxWidth) {
        return abbreviate(str, 0, maxWidth);
    }
	public static String abbreviate(String str, int offset, int maxWidth) {
        if (str == null) {
            return null;
        }
        if (maxWidth < 4) {
            throw new IllegalArgumentException("Minimum abbreviation width is 4");
        }
        if (str.length() <= maxWidth) {
            return str;
        }
        if (offset > str.length()) {
            offset = str.length();
        }
        if ((str.length() - offset) < (maxWidth - 3)) {
            offset = str.length() - (maxWidth - 3);
        }
        if (offset <= 4) {
            return str.substring(0, maxWidth - 3) + "...";
        }
        if (maxWidth < 7) {
            throw new IllegalArgumentException("Minimum abbreviation width with offset is 7");
        }
        if ((offset + (maxWidth - 3)) < str.length()) {
            return "..." + abbreviate(str.substring(offset), maxWidth - 3);
        }
        return "..." + str.substring(str.length() - (maxWidth - 3));
    }

}
